package com.youi.util;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 框架基础代码生成工具类
 * @author erdong.Chan
 *
 */
public class YouiCreateClassUtil {

    private static String PATH = "src/main/java";// maven项目文件路径

    // private static String PATH="src/"; 普通项目路径

    public static void main(String[] args) throws Exception {
        YouiCreateClassUtil.createdMybatis("Userorderexcel", "订单导出历史");
//         YouiCreateClassUtil.createdMybatisXML("Leaderwithdraw");
        // YouiCreateClassUtil.createdController("Test1", "提现信息");
//    	createdAllEntity("lawfirmdb","Erdong.Chen");
//    	createdMybatisAll();
    }

    public static void createdAllEntity(String dbName,String author) throws Exception {
    	//驱动
    	String DRIVER_NAME = "com.mysql.jdbc.Driver";
        //数据库连接地址
        String URL = "jdbc:mysql://localhost:3306/"+dbName+"?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC";
        //用户名
        String USER_NAME = "root";
        //密码
        String PASSWORD = "9889998";
        //Class.forName(DRIVER_NAME);
        //数据库连接对象
        Connection connection = DriverManager.getConnection(URL, USER_NAME, PASSWORD);
        String sql = "select table_name ,table_comment from information_schema.tables where table_schema='"+dbName+"'";
		Statement statement = connection.createStatement();
		ResultSet result = statement.executeQuery(sql);

		while(result.next()) {
			//获取表名和注释
			String tableName=result.getString("table_name");
			String tableComment=result.getString("table_comment");
			//查询表结构
			Statement st = connection.createStatement();
			sql="select COLUMN_NAME,DATA_TYPE,COLUMN_COMMENT from information_schema.COLUMNS where table_schema='"+dbName+"' and table_name = '"+tableName+"'";
			ResultSet rs = st.executeQuery(sql);
			List<Centity> centities=new ArrayList<Centity>();
			while(rs.next()) {
				centities.add(new Centity(rs.getString("COLUMN_NAME"), rs.getString("DATA_TYPE"), rs.getString("COLUMN_COMMENT")));
			}
			st.close();//关闭
			
			creadEntityFile(PATH, author,tableName,tableComment,centities);
		}
		statement.close();//关闭
    }
    
    public static void createdHibernate(String className, String memo) throws ClassNotFoundException {
        YouiCreateClassUtil.createdHibernateXML(className);
        YouiCreateClassUtil.createdDao(className);
        YouiCreateClassUtil.createdDaoImpl(className);
        YouiCreateClassUtil.createdService(className);
        YouiCreateClassUtil.createdServiceImpl(className);
        YouiCreateClassUtil.createdController(className, memo);
    }

    public static void createdHibernateAll() {
         File root = new File(YouiCreateClassUtil.PATH + "/com/youi/entity");
         File[] files = root.listFiles();
        for ( File file : files) {
             String fileName = file.getName();
             int index = fileName.indexOf(".");
             String className = file.getName().substring(0, index);
            System.out.println(className);
            try {
                YouiCreateClassUtil.createdHibernate(className, className);
            } catch ( ClassNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    public static void createdMybatis(String className, String memo) throws ClassNotFoundException {
        YouiCreateClassUtil.createdDao(className);
        YouiCreateClassUtil.createdMybatisXML(className);
        YouiCreateClassUtil.createdService(className);
        YouiCreateClassUtil.createdServiceImpl(className);
        YouiCreateClassUtil.createdController(className, memo);
    }

    public static void createdMybatisSqlserver(String className, String memo) throws ClassNotFoundException {
        YouiCreateClassUtil.createdDao(className);
        YouiCreateClassUtil.createdMybatisXMLSqlServer(className);
        YouiCreateClassUtil.createdService(className);
        YouiCreateClassUtil.createdServiceImpl(className);
        YouiCreateClassUtil.createdController(className, memo);
    }

    public static void createdMybatisAll() {
         File root = new File(YouiCreateClassUtil.PATH + "/com/youi/entity");
         File[] files = root.listFiles();
        for ( File file : files) {
             String fileName = file.getName();
             int index = fileName.indexOf(".");
             String className = file.getName().substring(0, index);
            System.out.println(className);
            try {
                YouiCreateClassUtil.createdMybatis(className, className);
            } catch ( ClassNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    /**
     * 创建DAO层接口类
     * @param className
     */
    public static void createdDao(String className) {
        try {

             String content = "package com.youi.dao;\n\n" + "import com.youi.entity." + className + ";\n\n"
                    + "public interface " + className + "Dao extends BaseDao<" + className + ">{\n\n" + "}";
             File f = new File(YouiCreateClassUtil.PATH + "/com/youi/dao/" + className + "Dao.java");
            if (f.exists()) {
                System.out.println("文件存在");
            } else {
                System.out.println("文件不存在");
                f.createNewFile();// 不存在则创建
            }
             BufferedWriter output = new BufferedWriter(new FileWriter(f));
            output.write(content);
            output.close();
        } catch ( Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 创建DAO层实现类
     * @param className
     */
    public static void createdDaoImpl(String className) {
        try {

             String content = "package com.youi.dao.impl;\n\n" +

                    "import org.springframework.stereotype.Repository;\n\n" +

                    "import com.youi.dao." + className + "Dao;\n" + "import com.youi.entity." + className + ";\n\n" +

                    "@Repository\n" + "public class " + className + "DaoImpl extends BaseDaoImpl<" + className
                    + "> implements " + className + "Dao{\n\n" +

                    "    @Override" + "    protected Class<" + className + "> getEntityClass() {\n"
                    + "       // TODO Auto-generated method stub\n" + "		return " + className + ".class;\n"
                    + "	 }\n\n" +

                    "}";
             File f = new File(YouiCreateClassUtil.PATH + "/com/youi/dao/impl/" + className + "DaoImpl.java");
            if (f.exists()) {
                System.out.println("文件存在");
            } else {
                System.out.println("文件不存在");
                f.createNewFile();// 不存在则创建
            }
             BufferedWriter output = new BufferedWriter(new FileWriter(f));
            output.write(content);
            output.close();
        } catch ( Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 创建服务层接口类
     * @param className
     */
    public static void createdService(String className) {
        try {

             String content = "package com.youi.service;\n\n" +

                    "import com.youi.entity." + className + ";\n\n" +

                    "public interface " + className + "Service extends BaseService<" + className + ">{\n\n" +

                    "}";
             File f = new File(YouiCreateClassUtil.PATH + "/com/youi/service/" + className + "Service.java");
            if (f.exists()) {
                System.out.println("文件存在");
            } else {
                System.out.println("文件不存在");
                f.createNewFile();// 不存在则创建
            }
             BufferedWriter output = new BufferedWriter(new FileWriter(f));
            output.write(content);
            output.close();
        } catch ( Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 创建服务层实现类
     * @param className
     */
    public static void createdServiceImpl(String className) {
        try {
             String classCommontName =
                    className.substring(0, 1).toLowerCase() + className.substring(1, className.length());// 获取驼峰变量名
             String content = "package com.youi.service.impl;\n\n" +

                    "import org.springframework.beans.factory.annotation.Autowired;\n"
                    + "import org.springframework.stereotype.Service;\n\n" +

                    "import com.youi.dao." + className + "Dao;\n" + "import com.youi.entity." + className + ";\n"
                    + "import com.youi.service." + className + "Service;\n\n" +

                    "@Service\n" + "public class " + className + "ServiceImpl extends BaseServiceImpl<" + className
                    + "> implements " + className + "Service{\n" + "		\n" + "		private " + className + "Dao "
                    + classCommontName + "Dao;\n" + "		\n" + "		@Autowired\n"
                    + "		public void setfaultRecordDao(" + className + "Dao " + classCommontName + "Dao){\n"
                    + "			this." + classCommontName + "Dao=" + classCommontName + "Dao;\n"
                    + "			super.setBaseDAO(" + classCommontName + "Dao);\n" + "		}\n" + "}";
             File f =
                    new File(YouiCreateClassUtil.PATH + "/com/youi/service/impl/" + className + "ServiceImpl.java");
            if (f.exists()) {
                System.out.println("文件存在");
            } else {
                System.out.println("文件不存在");
                f.createNewFile();// 不存在则创建
            }
             BufferedWriter output = new BufferedWriter(new FileWriter(f));
            output.write(content);
            output.close();
        } catch ( Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 创建hb对象映射文件
     * @param className
     * @throws ClassNotFoundException
     */
    public static void createdHibernateXML(String className) throws ClassNotFoundException {

        try {

            String content = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
                    + "<!DOCTYPE hibernate-mapping PUBLIC \"-//Hibernate/Hibernate Mapping DTD 3.0//EN\"\n"
                    + "\"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd\">\n" + "<!-- \n"
                    + "	Mapping file autogenerated by MyEclipse Persistence Tools\n" + "-->\n" + "<hibernate-mapping>\n"
                    + "	<class name=\"com.youi.entity." + className + "\" table=\"" + className.toLowerCase() + "\">\n";

             Class cls = Class.forName("com.youi.entity." + className);
             Field[] fields = cls.getDeclaredFields();
            for (int i = 0; i < fields.length; i++) {
                 Field field = fields[i];
                 String type = field.getType().toString();
                 String name = field.getName();
                if (i == 0) {
                    content += "		<id name=\"" + name + "\" type=\"" + type.substring(6, type.length()) + "\">\n"
                            + "			<column name=\"" + name + "\" />\n"
                            + "			<generator class=\"native\" />\n" + "		</id>\n";
                } else {
                    content += "		<property name=\"" + name + "\" type=\"" + type.substring(6, type.length())
                            + "\">\n" + "			<column name=\"" + name + "\" >\n" + "			</column>\n"
                            + "		</property>\n";
                }
            }
            content += "	</class>\n" + "</hibernate-mapping>";
             File f = new File(YouiCreateClassUtil.PATH + "/com/youi/entity/" + className + ".hbm.xml");
            if (f.exists()) {
                System.out.println("文件存在");
            } else {
                System.out.println("文件不存在");
                f.createNewFile();// 不存在则创建
            }
             BufferedWriter output = new BufferedWriter(new FileWriter(f));
            output.write(content);
            output.close();
        } catch ( Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 创建mybatis xml文件 mysql数据库链接方式
     * @param className
     * @throws ClassNotFoundException
     */
    public static void createdMybatisXML(String className) throws ClassNotFoundException {
        try {
             Class cls = Class.forName("com.youi.entity." + className);
             Field[] fields = cls.getDeclaredFields();
            String columnList = "";
             Map<String, String> params = new HashMap<>();
            for (int i = 0; i < fields.length; i++) {
                 Field field = fields[i];
                 Class type = field.getType();
                 String name = field.getName();
                 String value = YouiCreateClassUtil.getMybatisJdbcType(type);
                params.put(name, value);
                columnList += "," + name;
            }
            if (columnList.length() > 0) {
                columnList = columnList.substring(1, columnList.length());
            }
            if (params != null) {
                String content = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"
                        + "<!DOCTYPE mapper PUBLIC \"-//mybatis.org//DTD Mapper 3.0//EN\" \"http://mybatis.org/dtd/mybatis-3-mapper.dtd\" >\n"
                        + "<mapper namespace=\"com.youi.dao." + className + "Dao\" >\n" + "  <resultMap id=\""
                        + className + "\" type=\"com.youi.entity." + className + "\" >\n"
                        + "    <id column=\"id\" property=\"id\" jdbcType=\"BIGINT\" />\n";
                for ( String key : params.keySet()) {
                    if (!key.equals("id")) {
                        content += "    <result column=\"" + key + "\" property=\"" + key + "\" jdbcType=\""
                                + params.get(key) + "\" />\n";
                    }
                }
                content += "  </resultMap>\n";
                content += "  <sql id=\"Base_Column_List\" >\n" + "  	" + columnList + "\n" + "  </sql>\n";
                content += "  <!-- 根据id查询 -->\n" + "  <select id=\"get\" resultMap=\"" + className
                        + "\" parameterType=\"java.lang.Long\" >\n" + "    select \n"
                        + "    <include refid=\"Base_Column_List\" />\n" + "    from " + className.toLowerCase() + "\n"
                        + "    where id = #{id,jdbcType=BIGINT}\n" + "  </select>\n";
                content += "  <!-- 根据对象删除 -->\n" + "  <delete id=\"delete\"  parameterType=\"com.youi.entity."
                        + className + "\" >\n" + "    delete from " + className.toLowerCase() + "\n"
                        + "    where id = #{id,jdbcType=BIGINT}\n" + "  </delete>\n" + "  <!-- 根据id删除 -->\n"
                        + "  <delete id=\"delById\"  parameterType=\"java.lang.Long\" >\n" + "    delete from "
                        + className.toLowerCase() + "\n" + "    where id = #{id,jdbcType=BIGINT}\n" + "  </delete>\n"
                        + "  <!-- 根据id批量删除 -->\n" + "   <delete id=\"deleteAll\"   parameterType=\"java.util.List\" >\n"
                        + "    delete from " + className.toLowerCase() + "\n" + "	    where id in  \n"
                        + "	    <foreach collection =\"list\" item=\"item\" index= \"index\" open=\"(\" close=\")\" separator =\",\">\n"
                        + "		       #{item.id,jdbcType=BIGINT}\n" + "		 </foreach>\n" + "  </delete>\n";
                content += "<!-- 保存或修改 -->\n"
                        + "  <update id=\"saveOrUpdate\" useGeneratedKeys=\"true\" keyProperty=\"id\" parameterType=\"com.youi.entity."
                        + className + "\" >\n" + "     <if test=\"id == null\" >\n" + "        insert into "
                        + className.toLowerCase() + "\n"
                        + "	    <trim prefix=\"(\" suffix=\")\" suffixOverrides=\",\" >\n";
                for ( String key : params.keySet()) {
                    content += "		      <if test=\"" + key + " != null\" >\n" + "		        " + key + ",\n"
                            + "		      </if>\n";
                }
                content +=
                        "	    </trim>\n" + "	    <trim prefix=\"values (\" suffix=\")\" suffixOverrides=\",\" >\n";
                for ( String key : params.keySet()) {
                    content += "		      <if test=\"" + key + " != null\" >\n" + "		        #{" + key
                            + ",jdbcType=" + params.get(key) + "},\n" + "		      </if>\n";
                }
                content += "	    </trim>\n" + "      </if>\n";
                content += "      <if test=\"id != null\" >\n" + "         update " + className.toLowerCase() + "\n"
                        + "		    <set >\n";
                for ( String key : params.keySet()) {
                    if (!key.equals("id")) {
                        content += "		      <if test=\"" + key + " != null\" >\n" + "		        " + key
                                + " = #{" + key + ",jdbcType=" + params.get(key) + "},\n" + "		      </if>\n";
                    }
                }
                content += "		    </set>\n" + "		    where id = #{id,jdbcType=BIGINT}\n" + "      </if>\n"
                        + "  </update>\n" + "  <!-- 保存或修改集合 -->\n"
                        + "  <update id=\"saveOrUpdateAll\" useGeneratedKeys=\"true\" keyProperty=\"id\"  parameterType=\"java.util.List\" >\n"
                        + "  		<if test=\"list[0].id==null\" >\n" + "  			insert into "
                        + className.toLowerCase() + "\n" + "	           (" + columnList + ")\n"
                        + "	            values\n"
                        + "	            <foreach collection =\"list\" item=\"item\" index= \"index\" separator =\",\">\n"
                        + "	                 (\n";
                 String[] columnArr = columnList.split(",");
                for (int i = 0; i < columnArr.length; i++) {
                     String key = columnArr[i];
                    if (i != columnArr.length - 1) {// 不是最后一个 后面加逗号
                        content += "	                  #{item." + key + ",jdbcType=" + params.get(key) + "},\n";
                    } else {
                        content += "	                  #{item." + key + ",jdbcType=" + params.get(key) + "}\n";
                    }
                }
                content += "	                 )\n" + "	             </foreach>\n" + "  		 </if>\n"
                        + "  		 <if test=\"list[0].id!=null\" >\n"
                        + "  			 	<foreach collection =\"list\" item=\"item\" index= \"index\" separator =\";\">\n"
                        + "  			 		 update " + className.toLowerCase() + "\n"
                        + "				    <set >\n";
                for ( String key : params.keySet()) {
                    if (!key.equals("id")) {
                        content += "				      <if test=\"item." + key + " != null\" >\n"
                                + "				        " + key + " = #{item." + key + ",jdbcType=" + params.get(key)
                                + "},\n" + "				      </if>\n";
                    }
                }
                content += "				    </set>\n" + "				    where id = #{item.id,jdbcType=BIGINT}\n"
                        + "			     </foreach>\n" + "  		 </if>\n" + "  </update>\n";
                String resStr = " resultMap=\"" + className + "\" parameterType=\"java.util.Map\" >\n";
                String topstr = "    select \n" + "    <include refid=\"Base_Column_List\" />\n" + "    from "
                        + className.toLowerCase() + " where 1=1\n";
                 String paramstr = "    	<if test=\"params!= null\" >\n" + "    		 and \n"
                        + "    			<trim  suffixOverrides=\" and \" >\n"
                        + "    				<foreach collection =\"params.keys\" item=\"key\" index= \"index\" separator =\" and \" >\n"
                        + "    				<if test=\"params[key] instanceof java.util.Collection\" >\n"
                        + "    					${key} in \n"
                        + "    					<trim  prefix=\"(\"  suffix=\")\" suffixOverrides=\",\" >\n"
                        + "	    					<foreach collection =\"params[key]\" item=\"val\" index= \"index\" separator =\",\" >\n"
                        + "	    						#{val}\n" + "	    					</foreach>\n"
                        + "    					</trim>\n" + "    				</if>\n"
                        + "    				<if test=\"!params[key] instanceof java.util.Collection\" >\n"
                        + "    					${key}= #{params[${key}]}\n" + "    				</if>\n"
                        + "    				</foreach>\n" + "    			</trim>\n" + "		</if>\n";
                content += "\n" + "  <!-- 根据params查询 返回单个数据-->\n" + "  <select id=\"getObject\"" + resStr + topstr
                        + paramstr;
                content += "	 limit 0,1\n" + "  </select>\n";
                content += "\n" + "    <!-- 根据params查询  返回list-->\n" + "  <select id=\"getObjectList\"" + resStr
                        + topstr + paramstr + "  </select>\n";
                content += "\n" + "  <!-- 根据params(匹配) searchPram(模糊字段) sortPram(排序) 查询  返回单个数据-->\n"
                        + "  <select id=\"getByParam\"" + resStr + topstr + paramstr;
                 String searchstr = "    	<if test=\"searchParams != null\" >\n" + "    		 and (\n"
                        + "    			<foreach collection =\"searchParams.keys\" item=\"key\" index= \"index\" separator =\" and \" >\n"
                        + "    				<if test=\"searchParams[key] instanceof java.util.Collection\" >\n"
                        + "	    				<trim suffixOverrides=\" or \" >\n"
                        + "		    				<foreach collection =\"searchParams[key]\" item=\"val\" index= \"index\" separator =\" or \" >\n"
                        + "		    					${key} like  '%' #{val} '%'\n"
                        + "		    				</foreach>\n" + "	    				</trim>\n"
                        + "	    			</if>\n"
                        + "	    			<if test=\"!searchParams[key] instanceof java.util.Collection\" >\n"
                        + "	    					${key} like '%' #{searchParams[${key}]} '%'\n"
                        + "	    			</if>\n" + "    			</foreach>\n" + "    			)\n"
                        + "    	</if>\n";
                 String sortstr = "    	<if test=\"sortParams != null\" >\n" + "    		order by\n"
                        + "    		<trim suffixOverrides=\",\">\n"
                        + "    			<foreach collection =\"sortParams.keys\" item=\"key\" index= \"index\"  separator=\",\">\n"
                        + "	    			${key}  ${sortParams[key]}   \n" + "    			</foreach>\n"
                        + "    		</trim>\n" + "    	</if>	\n";
                content += searchstr + sortstr + "	limit 0,1\n" + "  </select>\n";
                content += "\n" + "	<!-- 根据params(匹配) searchPram(模糊字段) sortPram(排序) 查询  返回多个数据-->\n"
                        + "	<select id=\"getByParams\"" + resStr + topstr + paramstr + searchstr + sortstr
                        + "  </select>\n";
                content += "\n"
                        + "	<!-- 根据params(匹配) searchPram(模糊字段) sortPram(排序)  gtParams(大于) ltParams(小于) 查询  返回单个数据-->\n"
                        + "	<select id=\"getByParamss\"" + resStr + topstr + paramstr + searchstr;
                 String gtglstr = "    	<if test=\"gtParams != null\" >\n" + "    		and\n"
                        + "    		<trim suffixOverrides=\" and \">\n"
                        + "    			<foreach collection =\"gtParams.keys\" item=\"key\" index= \"index\"  separator=\" and \">\n"
                        + "	    			  ${key}  &gt;= #{gtParams[${key}]}\n" + "    			</foreach>\n"
                        + "    		</trim>\n" + "    	</if>\n" + "    	<if test=\"ltParams != null\" >\n"
                        + "    		and\n" + "    		<trim suffixOverrides=\" and \">\n"
                        + "    			<foreach collection =\"ltParams.keys\" item=\"key\" index= \"index\"  separator=\" and \">\n"
                        + "	    			 ${key} &lt;= #{ltParams[${key}]}\n" + "    			</foreach>\n"
                        + "    		</trim>\n" + "    	</if>\n";
                content += gtglstr + sortstr + "    limit 0,1\n" + "	</select>\n";
                content += "\n"
                        + "   <!-- 根据params(匹配) searchPram(模糊字段) sortPram(排序) pageIndex(页数) pageNum(数量) gtParams(大于) ltParams(小于) 查询  返回多个数据-->\n"
                        + "  <select id=\"getByParamsList\"" + resStr + topstr + paramstr + searchstr + gtglstr
                        + sortstr;
                 String pagestr = "    <if test=\"pageIndex!=null and pageNum !=null\" >\n"
                        + "    limit ${pageIndex},${pageNum}\n" + "    </if>\n";
                content += pagestr + "	</select>\n";
                content += "\n"
                        + "    <!-- 根据params(匹配) searchPram(模糊字段) sortPram(排序) gtParams(大于) ltParams(小于) 查询  返回所有数据-->\n"
                        + "  <select id=\"getByParamsAll\"" + resStr + topstr + paramstr + searchstr + gtglstr + sortstr
                        + "	</select>\n";
                resStr = " resultType=\"java.lang.Integer\" parameterType=\"java.util.Map\" >\n";
                topstr = "    select \n" + "    count(id) \n" + "    from " + className.toLowerCase() + " where 1=1\n";
                content += "\n" + "   <!-- 根据params查询  返回总数-->\n" + "  <select id=\"getCount\"" + resStr + topstr
                        + paramstr + "  </select>\n";
                content += "\n" + "    <!-- 根据params(匹配) searchPram(模糊字段) 查询  返回总数-->\n"
                        + "  <select id=\"getCountByParams\"" + resStr + topstr + paramstr + searchstr
                        + "  </select>\n";
                content += "\n" + "  <!-- 根据params(匹配) searchPram(模糊字段) gtParams(大于) ltParams(小于) 查询  返回总数-->\n"
                        + "  <select id=\"getCountByParamss\"" + resStr + topstr + paramstr + searchstr + gtglstr
                        + "  </select>\n";

                content += "</mapper>";
                 File f = new File(YouiCreateClassUtil.PATH + "/com/youi/dao/mapping/" + className + "Mapper.xml");
                if (f.exists()) {
                    System.out.println("文件存在");
                } else {
                    System.out.println("文件不存在");
                    f.createNewFile();// 不存在则创建
                }
                 BufferedWriter output = new BufferedWriter(new FileWriter(f));
                output.write(content.toString());
                output.close();
            }
        } catch ( Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 创建mybatis xml文件 sql server数据库链接方式
     * @param className
     * @throws ClassNotFoundException
     */
    public static void createdMybatisXMLSqlServer(String className) throws ClassNotFoundException {
        try {
             Class cls = Class.forName("com.youi.entity." + className);
             Field[] fields = cls.getDeclaredFields();
            String columnList = "";
             Map<String, String> params = new HashMap<>();
            for (int i = 0; i < fields.length; i++) {
                 Field field = fields[i];
                 Class type = field.getType();
                 String name = field.getName();
                 String value = YouiCreateClassUtil.getMybatisJdbcType(type);
                params.put(name, value);
                columnList += "," + name;
            }
            if (columnList.length() > 0) {
                columnList = columnList.substring(1, columnList.length());
            }
            if (params != null) {
                String content = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"
                        + "<!DOCTYPE mapper PUBLIC \"-//mybatis.org//DTD Mapper 3.0//EN\" \"http://mybatis.org/dtd/mybatis-3-mapper.dtd\" >\n"
                        + "<mapper namespace=\"com.youi.dao." + className + "Dao\" >\n" + "  <resultMap id=\""
                        + className + "\" type=\"com.youi.entity." + className + "\" >\n"
                        + "    <id column=\"id\" property=\"id\" jdbcType=\"BIGINT\" />\n";
                for ( String key : params.keySet()) {
                    if (!key.equals("id")) {
                        content += "    <result column=\"" + key + "\" property=\"" + key + "\" jdbcType=\""
                                + params.get(key) + "\" />\n";
                    }
                }
                content += "  </resultMap>\n";
                content += "  <sql id=\"Base_Column_List\" >\n" + "  	" + columnList + "\n" + "  </sql>\n";
                content += "  <!-- 根据id查询 -->\n" + "  <select id=\"get\" resultMap=\"" + className
                        + "\" parameterType=\"java.lang.Long\" >\n" + "    select \n"
                        + "    <include refid=\"Base_Column_List\" />\n" + "    from " + className.toLowerCase() + "\n"
                        + "    where id = #{id,jdbcType=BIGINT}\n" + "  </select>\n";
                content += "  <!-- 根据对象删除 -->\n" + "  <delete id=\"delete\"  parameterType=\"com.youi.entity."
                        + className + "\" >\n" + "    delete from " + className.toLowerCase() + "\n"
                        + "    where id = #{id,jdbcType=BIGINT}\n" + "  </delete>\n" + "  <!-- 根据id删除 -->\n"
                        + "  <delete id=\"delById\"  parameterType=\"java.lang.Long\" >\n" + "    delete from "
                        + className.toLowerCase() + "\n" + "    where id = #{id,jdbcType=BIGINT}\n" + "  </delete>\n"
                        + "  <!-- 根据id批量删除 -->\n" + "   <delete id=\"deleteAll\"   parameterType=\"java.util.List\" >\n"
                        + "    delete from " + className.toLowerCase() + "\n" + "	    where id in  \n"
                        + "	    <foreach collection =\"list\" item=\"item\" index= \"index\" open=\"(\" close=\")\" separator =\",\">\n"
                        + "		       #{item.id,jdbcType=BIGINT}\n" + "		 </foreach>\n" + "  </delete>\n";
                content += "<!-- 保存或修改 -->\n"
                        + "  <update id=\"saveOrUpdate\" useGeneratedKeys=\"true\" keyProperty=\"id\" parameterType=\"com.youi.entity."
                        + className + "\" >\n" + "     <if test=\"id == null\" >\n" + "        insert into "
                        + className.toLowerCase() + "\n"
                        + "	    <trim prefix=\"(\" suffix=\")\" suffixOverrides=\",\" >\n";
                for ( String key : params.keySet()) {
                    content += "		      <if test=\"" + key + " != null\" >\n" + "		        " + key + ",\n"
                            + "		      </if>\n";
                }
                content +=
                        "	    </trim>\n" + "	    <trim prefix=\"values (\" suffix=\")\" suffixOverrides=\",\" >\n";
                for ( String key : params.keySet()) {
                    content += "		      <if test=\"" + key + " != null\" >\n" + "		        #{" + key
                            + ",jdbcType=" + params.get(key) + "},\n" + "		      </if>\n";
                }
                content += "	    </trim>\n" + "      </if>\n";
                content += "      <if test=\"id != null\" >\n" + "         update " + className.toLowerCase() + "\n"
                        + "		    <set >\n";
                for ( String key : params.keySet()) {
                    if (!key.equals("id")) {
                        content += "		      <if test=\"" + key + " != null\" >\n" + "		        " + key
                                + " = #{" + key + ",jdbcType=" + params.get(key) + "},\n" + "		      </if>\n";
                    }
                }
                content += "		    </set>\n" + "		    where id = #{id,jdbcType=BIGINT}\n" + "      </if>\n"
                        + "  </update>\n" + "  <!-- 保存或修改集合 -->\n"
                        + "  <update id=\"saveOrUpdateAll\" useGeneratedKeys=\"true\" keyProperty=\"id\"  parameterType=\"java.util.List\" >\n"
                        + "  		<if test=\"list[0].id==null\" >\n" + "  			insert into "
                        + className.toLowerCase() + "\n" + "	           (" + columnList + ")\n"
                        + "	            values\n"
                        + "	            <foreach collection =\"list\" item=\"item\" index= \"index\" separator =\",\">\n"
                        + "	                 (\n";
                 String[] columnArr = columnList.split(",");
                for (int i = 0; i < columnArr.length; i++) {
                     String key = columnArr[i];
                    if (i != columnArr.length - 1) {// 不是最后一个 后面加逗号
                        content += "	                  #{item." + key + ",jdbcType=" + params.get(key) + "},\n";
                    } else {
                        content += "	                  #{item." + key + ",jdbcType=" + params.get(key) + "}\n";
                    }
                }
                content += "	                 )\n" + "	             </foreach>\n" + "  		 </if>\n"
                        + "  		 <if test=\"list[0].id!=null\" >\n"
                        + "  			 	<foreach collection =\"list\" item=\"item\" index= \"index\" separator =\";\">\n"
                        + "  			 		 update " + className.toLowerCase() + "\n"
                        + "				    <set >\n";
                for ( String key : params.keySet()) {
                    if (!key.equals("id")) {
                        content += "				      <if test=\"item." + key + " != null\" >\n"
                                + "				        " + key + " = #{item." + key + ",jdbcType=" + params.get(key)
                                + "},\n" + "				      </if>\n";
                    }
                }
                content += "				    </set>\n" + "				    where id = #{item.id,jdbcType=BIGINT}\n"
                        + "			     </foreach>\n" + "  		 </if>\n" + "  </update>\n";
                String resStr = " resultMap=\"" + className + "\" parameterType=\"java.util.Map\" >\n";
                String topstr = "    select \n" + "    <include refid=\"Base_Column_List\" />\n" + "    from "
                        + className.toLowerCase() + " where 1=1\n";
                 String paramstr = "    	<if test=\"params!= null\" >\n" + "    		 and \n"
                        + "    			<trim  suffixOverrides=\" and \" >\n"
                        + "    				<foreach collection =\"params.keys\" item=\"key\" index= \"index\" separator =\" and \" >\n"
                        + "    				<if test=\"params[key] instanceof java.util.Collection\" >\n"
                        + "    					${key} in \n"
                        + "    					<trim  prefix=\"(\"  suffix=\")\" suffixOverrides=\",\" >\n"
                        + "	    					<foreach collection =\"params[key]\" item=\"val\" index= \"index\" separator =\",\" >\n"
                        + "	    						#{val}\n" + "	    					</foreach>\n"
                        + "    					</trim>\n" + "    				</if>\n"
                        + "    				<if test=\"!params[key] instanceof java.util.Collection\" >\n"
                        + "    					${key}= #{params[${key}]}\n" + "    				</if>\n"
                        + "    				</foreach>\n" + "    			</trim>\n" + "		</if>\n";
                content += "\n" + "  <!-- 根据params查询 返回单个数据-->\n" + "  <select id=\"getObject\"" + resStr + topstr
                        + paramstr;
                content += "	order by id asc offset 0 rows fetch next 1 rows only \n" + "  </select>\n";
                content += "\n" + "    <!-- 根据params查询  返回list-->\n" + "  <select id=\"getObjectList\"" + resStr
                        + topstr + paramstr + "  </select>\n";
                content += "\n" + "  <!-- 根据params(匹配) searchPram(模糊字段) sortPram(排序) 查询  返回单个数据-->\n"
                        + "  <select id=\"getByParam\"" + resStr + topstr + paramstr;
                 String searchstr = "    	<if test=\"searchParams != null\" >\n" + "    		 and (\n"
                        + "    			<foreach collection =\"searchParams.keys\" item=\"key\" index= \"index\" separator =\" or \" >\n"
                        + "    				<if test=\"searchParams[key] instanceof java.util.Collection\" >\n"
                        + "	    				<trim suffixOverrides=\" or \" >\n"
                        + "		    				<foreach collection =\"searchParams[key]\" item=\"val\" index= \"index\" separator =\" or \" >\n"
                        + "		    					${key} like  '%'+ #{val} +'%'\n"
                        + "		    				</foreach>\n" + "	    				</trim>\n"
                        + "	    			</if>\n"
                        + "	    			<if test=\"!searchParams[key] instanceof java.util.Collection\" >\n"
                        + "	    					${key} like '%'+ #{searchParams[${key}]} +'%'\n"
                        + "	    			</if>\n" + "    			</foreach>\n" + "    			)\n"
                        + "    	</if>\n";
                 String sortstr = "    	<if test=\"sortParams != null\" >\n" + "    		order by\n"
                        + "    		<trim suffixOverrides=\",\">\n"
                        + "    			<foreach collection =\"sortParams.keys\" item=\"key\" index= \"index\"  separator=\",\">\n"
                        + "	    			${key}  ${sortParams[key]}   \n" + "    			</foreach>\n"
                        + "    		</trim>\n" + "    	</if>	\n";
                content += searchstr + sortstr + "	offset 0 rows fetch next 1 rows only \n" + "  </select>\n";
                content += "\n" + "	<!-- 根据params(匹配) searchPram(模糊字段) sortPram(排序) 查询  返回多个数据-->\n"
                        + "	<select id=\"getByParams\"" + resStr + topstr + paramstr + searchstr + sortstr
                        + "  </select>\n";
                content += "\n"
                        + "	<!-- 根据params(匹配) searchPram(模糊字段) sortPram(排序)  gtParams(大于) ltParams(小于) 查询  返回单个数据-->\n"
                        + "	<select id=\"getByParamss\"" + resStr + topstr + paramstr + searchstr;
                 String gtglstr = "    	<if test=\"gtParams != null\" >\n" + "    		and\n"
                        + "    		<trim suffixOverrides=\" and \">\n"
                        + "    			<foreach collection =\"gtParams.keys\" item=\"key\" index= \"index\"  separator=\" and \">\n"
                        + "	    			  ${key}  &gt;= #{gtParams[${key}]}\n" + "    			</foreach>\n"
                        + "    		</trim>\n" + "    	</if>\n" + "    	<if test=\"ltParams != null\" >\n"
                        + "    		and\n" + "    		<trim suffixOverrides=\" and \">\n"
                        + "    			<foreach collection =\"ltParams.keys\" item=\"key\" index= \"index\"  separator=\" and \">\n"
                        + "	    			 ${key} &lt;= #{ltParams[${key}]}\n" + "    			</foreach>\n"
                        + "    		</trim>\n" + "    	</if>\n";
                content += gtglstr + sortstr + "    offset 0 rows fetch next 1 rows only \n" + "	</select>\n";
                content += "\n"
                        + "   <!-- 根据params(匹配) searchPram(模糊字段) sortPram(排序) pageIndex(页数) pageNum(数量) gtParams(大于) ltParams(小于) 查询  返回多个数据-->\n"
                        + "  <select id=\"getByParamsList\"" + resStr + topstr + paramstr + searchstr + gtglstr
                        + sortstr;
                 String pagestr = "    <if test=\"pageIndex!=null and pageNum !=null\" >\n"
                        + "    offset ${pageIndex} rows fetch next ${pageNum} rows only \n" + "    </if>\n";
                content += pagestr + "	</select>\n";
                content += "\n"
                        + "    <!-- 根据params(匹配) searchPram(模糊字段) sortPram(排序) gtParams(大于) ltParams(小于) 查询  返回所有数据-->\n"
                        + "  <select id=\"getByParamsAll\"" + resStr + topstr + paramstr + searchstr + gtglstr + sortstr
                        + "	</select>\n";
                resStr = " resultType=\"java.lang.Integer\" parameterType=\"java.util.Map\" >\n";
                topstr = "    select \n" + "    count(id) \n" + "    from " + className.toLowerCase() + " where 1=1\n";
                content += "\n" + "   <!-- 根据params查询  返回总数-->\n" + "  <select id=\"getCount\"" + resStr + topstr
                        + paramstr + "  </select>\n";
                content += "\n" + "    <!-- 根据params(匹配) searchPram(模糊字段) 查询  返回总数-->\n"
                        + "  <select id=\"getCountByParams\"" + resStr + topstr + paramstr + searchstr
                        + "  </select>\n";
                content += "\n" + "  <!-- 根据params(匹配) searchPram(模糊字段) gtParams(大于) ltParams(小于) 查询  返回总数-->\n"
                        + "  <select id=\"getCountByParamss\"" + resStr + topstr + paramstr + searchstr + gtglstr
                        + "  </select>\n";

                content += "</mapper>";
                 File f = new File(YouiCreateClassUtil.PATH + "/com/youi/dao/mapping/" + className + "Mapper.xml");
                if (f.exists()) {
                    System.out.println("文件存在");
                } else {
                    System.out.println("文件不存在");
                    f.createNewFile();// 不存在则创建
                }
                 BufferedWriter output = new BufferedWriter(new FileWriter(f));
                output.write(content.toString());
                output.close();
            }
        } catch ( Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取jdbcType
     * @param type
     * @return
     */
    private static String getMybatisJdbcType(Class type) {
        String jdbcType = "";
        if (type.equals(String.class)) {// 如果是字符串
            jdbcType = "VARCHAR";
        } else if (type.equals(Long.class)) {// 如果是long
            jdbcType = "BIGINT";
        } else if (type.equals(Integer.class)) {// 如果是Integer
            jdbcType = "INTEGER";
        } else if (type.equals(Float.class)) {// 如果是Float
            jdbcType = "FLOAT";
        } else if (type.equals(Double.class)) {// 如果是DOUBLE
            jdbcType = "DOUBLE";
        } else if (type.equals(Date.class)) {// 如果是Date
            jdbcType = "TIMESTAMP";
        }
        return jdbcType;
    }

    /**
     * 创建控制层文件
     * @param className
     * @param memo
     */
    public static void createdController(String className, String memo) {
        try {
             Class cls = Class.forName("com.youi.entity." + className);
            String methodFiled = "";
             Field[] fields = cls.getDeclaredFields();
            boolean containGmt = false;
            boolean containGmtStart = false;
            boolean containGmtEnd = false;
            boolean containGmtModify = false;
            for (int i = 0; i < fields.length; i++) {
                 Field field = fields[i];
                 String type = field.getType().toString();
                 String name = field.getName();
                if (name.equals("gmtCreated")) {
                    containGmt = true;
                } else if (name.equals("gmtStart")) {
                    containGmtStart = true;
                    methodFiled += "String " + name + ",";
                } else if (name.equals("gmtEnd")) {
                    containGmtEnd = true;
                    methodFiled += "String " + name + ",";
                } else if (name.equals("gmtModify")) {
                    containGmtModify = true;
                } else {
                    methodFiled += type.substring(0, type.length()) + " " + name + ",";
                }
            }
            methodFiled = methodFiled.substring(0, methodFiled.length() - 1);
             String classCommontName =
                    className.substring(0, 1).toLowerCase() + className.substring(1, className.length());// 获取驼峰变量名
            String content = "package com.youi.web;\n\n" +

                    "import java.text.ParseException;\n" + "import java.util.Date;\n" + "import java.util.List;\n"
                    + "import java.util.HashMap;\n" + "import java.util.Map;\n\n" +

                    "import javax.servlet.http.HttpServletRequest;\n\n" +

                    "import org.springframework.beans.factory.annotation.Autowired;\n"
                    + "import org.springframework.stereotype.Controller;\n"
                    + "import org.springframework.ui.ModelMap;\n"
                    + "import org.springframework.web.bind.annotation.RequestMapping;\n"
                    + "import org.springframework.web.bind.annotation.ResponseBody;\n" +

                    "import com.youi.exception.BusinessException;\n" + "import com.youi.manage.HttpRequestManage;\n"
                    + "import com.youi.common.DelStatus;\n" + "import com.youi.service." + className + "Service;\n"
                    + "import com.youi.entity." + className + ";\n" + "import com.youi.common.Common;\n"
                    + "import com.youi.util.CommonInfoUtil;\n" + "import com.youi.util.DateUtil;\n"
                    + "import com.youi.util.JsonUtil;\n" + "import com.youi.util.ObjectUtil;\n"
                    + "import com.youi.util.Page;\n\n" +

                    "/**\n" + "* " + memo + "控制层\n" + "* @author Administrator\n" + "*/\n" + "@Controller\n"
                    + "public class " + className + "Controller  extends HttpRequestManage{\n\n" +

                    "		@Autowired\n" + "		private " + className + "Service " + classCommontName
                    + "Service;\n\n" +

                    "		/**\n" + "		 *添加或编辑" + memo + "\n" + "		*/\n" + "		@ResponseBody\n"
                    + "		@RequestMapping(\"addOrEdit" + className + "\")\n" + "		public String addOrEdit"
                    + className
                    + "(ModelMap modelMap,HttpServletRequest request)throws BusinessException,ParseException{\n"
                    + "			Long id=optLong(\"id\",request);\n" + "			" + className + " " + classCommontName
                    + "=null;\n" + "			if (id!=null) {\n" + "				" + classCommontName + "="
                    + classCommontName + "Service.get(id);\n" + "			}else {\n" + "				"
                    + classCommontName + "=new " + className + "();\n" + "				" + classCommontName
                    + ".setDelStatus(DelStatus.NODEL);\n";
            if (containGmt) {
                content += "				" + classCommontName + ".setGmtCreated(new Date());\n";
            }
            content += "			}\n";
            for (int i = 1; i < fields.length; i++) {
                 Field field = fields[i];
                String type = field.getType().toString();
                type = type.substring(type.lastIndexOf(".") + 1, type.length());
                 String name = field.getName();
                 String upperName = name.substring(0, 1).toUpperCase() + name.substring(1, name.length());// 获取大写开头变量名
                if (field.getType().equals(new Date().getClass()) || field.getType().equals(Timestamp.class)
                        || name.equals("delStatus")) {
                    continue;
                }
                content += "			" + type + " " + name + "=opt" + type + "(\"" + name + "\",request);\n";
                content += "			if (" + name + "!=null){\n";
                content += "				" + classCommontName + ".set" + upperName + "(" + name + ");\n";
                content += "			}\n";

            }
            if (containGmtStart) {
                content += "			Date gmtStart=optDate(\"gmtStart\",request,\"yyyy-MM-dd HH:mm:ss\");\n";
                content += "			if (gmtStart!=null&&gmtStart.length()>0){\n";
                content +=
                        "				" + classCommontName + ".setGmtStart(DateUtil.simpdfyMd.parse(gmtStart));\n";
                content += "			}\n";
            }
            if (containGmtEnd) {
                content += "			Date gmtEnd=optDate(\"gmtEnd\",request,\"yyyy-MM-dd HH:mm:ss\");\n";
                content += "			if (gmtEnd!=null&&gmtEnd.length()>0){\n";
                content += "				" + classCommontName + ".setGmtEnd(DateUtil.simpdfyMd.parse(gmtEnd));\n";
                content += "			}\n";
            }
            if (containGmtModify) {
                content += "			" + classCommontName + ".setGmtModify(new Date());\n";
            }
            content += "			" + classCommontName + "Service.saveOrUpdate(" + classCommontName + ");\n"
                    + "			return JsonUtil.toJson(CommonInfoUtil.SUCCESS, \"操作完成\");\n" + "		}\n\n" +
                    /*
                    "		/**\n"+
                    "		 *删除"+memo+"\n"+
                    "		\n"+
                    "		@ResponseBody\n"+
                    "		@RequestMapping(\"del"+className+"\")\n"+
                    "		public String del"+className+"(ModelMap modelMap,HttpServletRequest request,Long id){\n"+
                    "			if (id!=null) {\n"+
                    "				"+className+" "+classCommontName+"="+classCommontName+"Service.get(id);\n"+
                    "				if ("+classCommontName+"!=null) {\n"+
                    "					"+classCommontName+".setDelStatus(DelStatus.DEL);\n"+
                    "					"+classCommontName+"Service.saveOrUpdate("+classCommontName+");\n"+
                    "				}\n"+
                    "				modelMap.put(CommonInfoUtil.JSONCODE, CommonInfoUtil.SUCCESS);//msg=1	操作完成\n"+
                    "			}else {\n"+
                    "				modelMap.put(CommonInfoUtil.JSONCODE, CommonInfoUtil.PARAMERROR);//msg=-1 参数错误\n"+
                    "			}\n"+
                    "			return JsonUtil.toJson(modelMap);\n"+
                    "		}\n\n"+*/

                    "		/**\n" + "		 *批量删除" + memo + "\n" + "		*/\n" + "		@ResponseBody\n"
                    + "		@RequestMapping(\"del" + className + "ByIds\")\n" + "		public String del" + className
                    + "ByIds(ModelMap modelMap,HttpServletRequest request) throws BusinessException{\n"
                    + "			String ids=getString(\"ids\",request);\n"
                    + "			List<Long> idsList=ObjectUtil.getIdListByIds(ids);\n"
                    + "			if (idsList==null||idsList.size()==0) {\n"
                    + "				return JsonUtil.toJson(CommonInfoUtil.PARAMERROR, \"ids参数错误\");\n" + "			}\n"
                    + "			Map<String, Object> params=new HashMap<String, Object>();\n"
                    + "			params.put(Common.DELSTATUS, DelStatus.NODEL);\n"
                    + "			params.put(Common.ID, idsList);\n" + "			List<" + className + "> "
                    + classCommontName + "List= " + classCommontName + "Service.getByParams(params);\n"
                    + "			if (" + classCommontName + "List==null||" + classCommontName + "List.size()==0) {\n"
                    + "				return JsonUtil.toJson(CommonInfoUtil.NULLDATA, \"空数据\");\n" + "			}\n"
                    + "			for (" + className + " " + classCommontName + " : " + classCommontName + "List) {\n"
                    + "				" + classCommontName + ".setDelStatus(DelStatus.DEL);\n" + "			}\n"
                    + "			" + classCommontName + "Service.saveOrUpdateAll(" + classCommontName + "List);\n"
                    + "			return JsonUtil.toJson(CommonInfoUtil.SUCCESS, \"操作完成\");\n" + "		}\n\n" +

                    "		/**\n" + "		 * 分页查询" + memo + "\n" + "		*/\n" + "		@ResponseBody\n"
                    + "		@RequestMapping(\"get" + className + "\")\n" + "		public String get" + className
                    + "(ModelMap modelMap,HttpServletRequest request) throws BusinessException,ParseException{\n"
                    + "			Integer pageIndex=optInteger(\"pageIndex\",request,1);\n"
                    + "			Integer pageNum=optInteger(\"pageNum\",request,10);\n"
                    + "			String des=optString(\"des\",request,Common.DESC);\n"
                    + "			String pms=optString(\"pms\",request);\n"
                    + "			Date start=optDate(\"start\",request,\"yyyy-MM-dd HH:mm:ss\");\n"
                    + "			Date end=optDate(\"end\",request,\"yyyy-MM-dd HH:mm:ss\");\n"
                    + "			Map<String, Object> prams=new HashMap<String, Object>();\n"
                    + "			prams.put(Common.DELSTATUS, DelStatus.NODEL);\n"
                    + "			Map<String, Object> sortPram=new HashMap<String, Object>();\n"
                    + "			sortPram.put(Common.ID,des);\n" + "			Map<String, Object> searchPram=null;\n"
                    + "			if (pms!=null) {\n" + "				searchPram=new HashMap<String, Object>();\n"
                    + "			}\n" + "			Map<String, Object> startTime=null;\n"
                    + "			if(start!=null){\n" + "				startTime=new HashMap<String, Object>();\n"
                    + "				startTime.put(Common.GMTCREATED,start);\n" + "			}\n"
                    + "			Map<String, Object> endTime=null;\n" + "			if(end!=null){\n"
                    + "				endTime=new HashMap<String, Object>();\n"
                    + "				endTime.put(Common.GMTCREATED,end);\n" + "			}\n" + "			List<"
                    + className + "> " + classCommontName + "List=" + classCommontName
                    + "Service.getByParamsList(prams, searchPram,sortPram,  (pageIndex-1)*pageNum, pageNum, startTime, endTime);\n"
                    + "			if (" + classCommontName + "List==null||" + classCommontName + "List.size()==0) {\n"
                    + "				return JsonUtil.toJson(CommonInfoUtil.NULLDATA, \"空数据\");\n" + "			}\n"
                    + "			Integer pageCount=" + classCommontName
                    + "Service.getCountByParamss(prams, searchPram, startTime, endTime);\n"
                    + "			modelMap.put(CommonInfoUtil.PAGECOUNT, Page.getCount(pageCount, pageNum));//pageCount  总页数\n"
                    + "			modelMap.put(CommonInfoUtil.PAGEINDEX, pageIndex);			//pageIndex     查询页数\n"
                    + "			modelMap.put(CommonInfoUtil.ALLCOUINT,pageCount);\n"
                    + "			modelMap.put(CommonInfoUtil.DATA, " + classCommontName
                    + "List);		//jsonObjectList json对象集合\n"
                    + "			return JsonUtil.toJson(CommonInfoUtil.SUCCESS, \"操作完成\",modelMap);\n" + "		}\n\n" +

                    "		/**\n" + "		 *根据id查询" + memo + "\n" + "		*/\n" + "		@ResponseBody\n"
                    + "		@RequestMapping(\"get" + className + "ById\")\n" + "		public String get" + className
                    + "ById(ModelMap modelMap,HttpServletRequest request) throws BusinessException{\n"
                    + "			Long id=getLong(\"id\",request);\n" + "			" + className + " " + classCommontName
                    + "=" + classCommontName + "Service.get(id);\n" + "			if (" + classCommontName + "==null) {\n"
                    + "				return JsonUtil.toJson(CommonInfoUtil.NULLDATA, \"空数据\");\n" + "			}\n"
                    + "			return JsonUtil.toJson(CommonInfoUtil.SUCCESS, \"操作完成\"," + classCommontName
                    + ");//jsonObject	json对象\n" + "		}\n\n" +

                    "		/**\n" + "		 * 查询所有" + memo + "\n" + "		 * @param modelMap\n"
                    + "		 * @param session\n" + "		 * @return\n" + "		 */\n" + "		@ResponseBody\n"
                    + "		@RequestMapping(\"getAll" + className + "\")\n" + "		public String getAll" + className
                    + "(ModelMap modelMap,HttpServletRequest request) throws BusinessException{\n" + "			List<"
                    + className + "> " + classCommontName + "List= " + classCommontName + "Service.getByParams(null);\n"
                    + "			if (" + classCommontName + "List==null||" + classCommontName + "List.size()==0) {\n"
                    + "				return JsonUtil.toJson(CommonInfoUtil.NULLDATA, \"空数据\");\n" + "			}\n"
                    + "			return JsonUtil.toJson(CommonInfoUtil.SUCCESS, \"操作完成\"," + classCommontName
                    + "List);//jsonObjectList	json对象集合\n" + "		}\n" + "}\n";

             File f = new File(YouiCreateClassUtil.PATH + "/com/youi/web/" + className + "Controller.java");
            if (f.exists()) {
                System.out.println("文件存在");
            } else {
                System.out.println("文件不存在");
                f.createNewFile();// 不存在则创建
            }
             BufferedWriter output = new BufferedWriter(new FileWriter(f));
            output.write(content);
            output.close();
        } catch ( Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 创建控制层文件-新
     * @param className
     * @param memo
     */
    public static void createdController2(String className, String memo) {
        try {
             Class cls = Class.forName("com.youi.entity." + className);
            String methodFiled = "";
             Field[] fields = cls.getDeclaredFields();
            boolean containGmt = false;
            boolean containGmtStart = false;
            boolean containGmtEnd = false;
            boolean containGmtModify = false;
            for (int i = 0; i < fields.length; i++) {
                 Field field = fields[i];
                 String type = field.getType().toString();
                 String name = field.getName();
                if (name.equals("gmtCreated")) {
                    containGmt = true;
                } else if (name.equals("gmtStart")) {
                    containGmtStart = true;
                    methodFiled += "String " + name + ",";
                } else if (name.equals("gmtEnd")) {
                    containGmtEnd = true;
                    methodFiled += "String " + name + ",";
                } else if (name.equals("gmtModify")) {
                    containGmtModify = true;
                } else {
                    methodFiled += type.substring(16, type.length()) + " " + name + ",";
                }
            }
            methodFiled = methodFiled.substring(0, methodFiled.length() - 1);
             String classCommontName =
                    className.substring(0, 1).toLowerCase() + className.substring(1, className.length());// 获取驼峰变量名
            String content = "package com.youi.web;\n\n" +

                    "import java.text.ParseException;\n" + "import java.util.Date;\n" + "import java.util.List;\n"
                    + "import java.util.HashMap;\n" + "import java.util.Map;\n\n" +

                    "import javax.servlet.http.HttpServletRequest;\n\n" +

                    "import org.springframework.beans.factory.annotation.Autowired;\n"
                    + "import org.springframework.stereotype.Controller;\n"
                    + "import org.springframework.ui.ModelMap;\n"
                    + "import org.springframework.web.bind.annotation.RequestMapping;\n"
                    + "import org.springframework.web.bind.annotation.ResponseBody;\n" +

                    "import com.youi.common.DelStatus;\n" + "import com.youi.service." + className + "Service;\n"
                    + "import com.youi.entity." + className + ";\n" + "import com.youi.common.Common;\n"
                    + "import com.youi.util.CommonInfoUtil;\n" + "import com.youi.util.DateUtil;\n"
                    + "import com.youi.util.JsonUtil;\n" + "import com.youi.util.ObjectUtil;\n"
                    + "import com.youi.util.Page;\n\n" +

                    "/**\n" + "* " + memo + "控制层\n" + "* @author Administrator\n" + "*/\n" + "@Controller\n"
                    + "public class " + className + "Controller{\n\n" +

                    "		@Autowired\n" + "		private " + className + "Service " + classCommontName
                    + "Service;\n\n" +

                    "		/**\n" + "		 *添加或编辑" + memo + "\n" + "		*/\n" + "		@ResponseBody\n"
                    + "		@RequestMapping(\"addOrEdit" + className + "\")\n" + "		public String addOrEdit"
                    + className + "(ModelMap modelMap,HttpServletRequest request," + methodFiled
                    + ")throws ParseException {\n" + "			" + className + " " + classCommontName + "=null;\n"
                    + "			if (id!=null) {\n" + "				" + classCommontName + "=" + classCommontName
                    + "Service.get(id);\n" + "			}else {\n" + "				" + classCommontName + "=new "
                    + className + "();\n" + "				" + classCommontName + ".setDelStatus(DelStatus.NODEL);\n";
            if (containGmt) {
                content += "				" + classCommontName + ".setGmtCreated(new Date());\n";
            }
            content += "			}\n" + "			if (" + classCommontName + "==null) {\n"
                    + "				return JsonUtil.toJson(CommonInfoUtil.NULLDATA,\"空数据\");\n" + "			}\n";
            for (int i = 1; i < fields.length; i++) {
                 Field field = fields[i];
                 String type = field.getType().toString();
                 String name = field.getName();
                 String upperName = name.substring(0, 1).toUpperCase() + name.substring(1, name.length());// 获取大写开头变量名
                if (field.getType().equals(new Date().getClass()) || field.getType().equals(Timestamp.class)
                        || name.equals("delStatus")) {
                    continue;
                }
                content += "			if (" + name + "!=null";
                if (field.getType().equals(String.class)) {
                    content += "&&" + name + ".length()>0";
                }
                content += "){\n";
                content += "				" + classCommontName + ".set" + upperName + "(" + name + ");\n";
                content += "			}\n";

            }
            if (containGmtStart) {
                content += "			if (gmtStart!=null&&gmtStart.length()>0){\n";
                content +=
                        "				" + classCommontName + ".setGmtStart(DateUtil.simpdfyMd.parse(gmtStart));\n";
                content += "			}\n";
            }
            if (containGmtEnd) {
                content += "			if (gmtEnd!=null&&gmtEnd.length()>0){\n";
                content += "				" + classCommontName + ".setGmtEnd(DateUtil.simpdfyMd.parse(gmtEnd));\n";
                content += "			}\n";
            }
            if (containGmtModify) {
                content += "			" + classCommontName + ".setGmtModify(new Date());\n";
            }
            content += "			" + classCommontName + "Service.saveOrUpdate(" + classCommontName + ");\n"
                    + "			return JsonUtil.toJson(CommonInfoUtil.SUCCESS,\"操作完成\");\n" + "		}\n\n"
                    + "		/**\n" + "		 *批量删除" + memo + "\n" + "		*/\n" + "		@ResponseBody\n"
                    + "		@RequestMapping(\"del" + className + "ByIds\")\n" + "		public String del" + className
                    + "ByIds(ModelMap modelMap,HttpServletRequest request,String ids){\n"
                    + "			if (ids == null||ids.length()==0) {\n"
                    + "				return JsonUtil.toJson(CommonInfoUtil.PARAMERROR,\"参数错误\");\n" + "			}\n"
                    + "			List<Long> idsList=ObjectUtil.getIdListByIds(ids);\n"
                    + "			if (idsList==null||idsList.size()==0) {\n"
                    + "				return JsonUtil.toJson(CommonInfoUtil.NULLDATA,\"空数据\");\n" + "			}\n"
                    + "			Map<String, Object> params=new HashMap<String, Object>();\n"
                    + "			params.put(\"id\", idsList);\n" + "			params.put(\"delStatus\", 0);\n"
                    + "			List<" + className + "> " + classCommontName + "List= " + classCommontName
                    + "Service.getByParams(params);\n" + "			if (" + classCommontName + "List==null||"
                    + classCommontName + "List.size()==0) {\n"
                    + "				return JsonUtil.toJson(CommonInfoUtil.NULLDATA,\"空数据\");\n" + "			}\n"
                    + "			for (" + className + " " + classCommontName + " : " + classCommontName + "List) {\n"
                    + "				" + classCommontName + ".setDelStatus(DelStatus.DEL);\n" + "			}\n"
                    + "			" + classCommontName + "Service.saveOrUpdateAll(" + classCommontName + "List);\n"
                    + "			return JsonUtil.toJson(CommonInfoUtil.SUCCESS,\"操作完成\");\n" + "		}\n\n"
                    + "		/**\n" + "		 * 分页查询" + memo + "\n" + "		*/\n" + "		@ResponseBody\n"
                    + "		@RequestMapping(\"get" + className + "\")\n" + "		public String get" + className
                    + "(ModelMap modelMap,HttpServletRequest request,Integer pageIndex,Integer pageNum,Integer pageCount,String des,String pms,String start,String end) throws ParseException {\n"
                    + "			if (pageIndex==null) {\n" + "				pageIndex=1;\n" + "			}\n"
                    + "			if (pageNum==null) {\n" + "				pageNum=10;\n" + "			}\n"
                    + "			Map<String, Object> prams=new HashMap<String, Object>();\n"
                    + "			prams.put(Common.DELSTATUS, DelStatus.NODEL);\n"
                    + "			Map<String, Object> sortPram=new HashMap<String, Object>();\n"
                    + "			sortPram.put(Common.ID,Common.DESC);\n" + "			if (des!=null&&des.length()>0) {\n"
                    + "				sortPram.put(Common.ID,des);\n" + "			}\n"
                    + "			Map<String, Object> searchPram=null;\n" + "			if (pms!=null&&pms.length()>0) {\n"
                    + "				searchPram=new HashMap<String, Object>();\n" + "			}\n"
                    + "			Map<String, Object> startTime=null;\n"
                    + "			if(start!=null&&start.length()>0){\n"
                    + "				startTime=new HashMap<String, Object>();\n"
                    + "				startTime.put(Common.GMTCREATED,  DateUtil.simpdfyMdHms.parse(start+\" 00:00:00\"));\n"
                    + "			}\n" + "			Map<String, Object> endTime=null;\n"
                    + "			if(end!=null&&end.length()>0){\n"
                    + "				endTime=new HashMap<String, Object>();\n"
                    + "				endTime.put(Common.GMTCREATED,  DateUtil.simpdfyMdHms.parse(end+\" 23:59:59\"));\n"
                    + "			}\n" + "			List<" + className + "> " + classCommontName + "List="
                    + classCommontName
                    + "Service.getByParamsList(prams, searchPram,sortPram,  (pageIndex-1)*pageNum, pageNum, startTime, endTime);\n"
                    + "			if (" + classCommontName + "List==null||" + classCommontName + "List.size()==0) {\n"
                    + "				return JsonUtil.toJson(CommonInfoUtil.NULLDATA,\"空数据\");\n" + "			}\n"
                    + "			pageCount=" + classCommontName
                    + "Service.getCountByParamss(prams, searchPram, startTime, endTime);\n"
                    + "			modelMap.put(CommonInfoUtil.PAGECOUNT, Page.getCount(pageCount, pageNum));//pageCount  总页数\n"
                    + "			modelMap.put(CommonInfoUtil.PAGEINDEX, pageIndex);			//pageIndex     查询页数\n"
                    + "			modelMap.put(CommonInfoUtil.ALLCOUINT,pageCount);\n"
                    + "			modelMap.put(CommonInfoUtil.DATA, " + classCommontName
                    + "List);		//jsonObjectList json对象集合\n"
                    + "			return JsonUtil.toJson(CommonInfoUtil.SUCCESS,\"操作完成\",modelMap);\n" + "		}\n\n" +

                    "		/**\n" + "		 *根据id查询" + memo + "\n" + "		*/\n" + "		@ResponseBody\n"
                    + "		@RequestMapping(\"get" + className + "ById\")\n" + "		public String get" + className
                    + "ById(ModelMap modelMap,HttpServletRequest request,Long id){\n" + "			if (id==null) {\n"
                    + "				return JsonUtil.toJson(CommonInfoUtil.PARAMERROR,\"参数错误\");\n" + "			}\n"
                    + "			" + className + " " + classCommontName + "=" + classCommontName + "Service.get(id);\n"
                    + "			if (" + classCommontName + "==null) {\n"
                    + "				return JsonUtil.toJson(CommonInfoUtil.NULLDATA,\"空数据\");\n" + "			}\n"
                    + "			return JsonUtil.toJson(CommonInfoUtil.SUCCESS,\"操作完成\"," + classCommontName + ");\n"
                    + "		}\n\n" + "		/**\n" + "		 * 查询所有" + memo + "\n" + "		 * @param modelMap\n"
                    + "		 * @param session\n" + "		 * @return\n" + "		 */\n" + "		@ResponseBody\n"
                    + "		@RequestMapping(\"getAll" + className + "\")\n" + "		public String getAll" + className
                    + "(ModelMap modelMap,HttpServletRequest request){\n" + "			List<" + className + "> "
                    + classCommontName + "List= " + classCommontName + "Service.getByParams(null);\n"
                    + "			if (" + classCommontName + "List==null||" + classCommontName + "List.size()==0) {\n"
                    + "				return JsonUtil.toJson(CommonInfoUtil.NULLDATA,\"空数据\");\n" + "			}\n"
                    + "			return JsonUtil.toJson(CommonInfoUtil.SUCCESS,\"操作完成\"," + classCommontName + "List);\n"
                    + "		}\n" + "}\n";

             File f = new File(YouiCreateClassUtil.PATH + "/com/youi/web/" + className + "Controller.java");
            if (f.exists()) {
                System.out.println("文件存在");
            } else {
                System.out.println("文件不存在");
                f.createNewFile();// 不存在则创建
            }
             BufferedWriter output = new BufferedWriter(new FileWriter(f));
            output.write(content);
            output.close();
        } catch ( Exception e) {
            e.printStackTrace();
        }
    }
    
	/**
	 * 创建Entity文件
	 */
	private static void creadEntityFile(String path,String author,String tableName,String tableComment,List<Centity> centities) {
		try {
			
			//表名首字母大写
			tableName=tableName.substring(0, 1).toUpperCase()+tableName.substring(1,tableName.length());
			
			if (tableName.equals("Sysuser")) {
				System.out.println("2222");
			}
            String content = 
            		"package com.youi.entity;\n\n"+
            		"import java.util.Date;\n\n"+	
            		"/**\n"+	
            		" * "+tableComment+"\n"+
            		" * "+tableName+" entity.@author "+author+"\n"+
            		" */\n"+	
                    "public class " + tableName + " implements java.io.Serializable {\n\n";
            //属性
            for (Centity centity : centities) {
            	content+="	private "+centity.getColumnType()+" "+centity.getColumnName()+";	//"+centity.getColumnCommond()+"\n";
			}
            content+="\n";
            //构造函数
            content+="	public "+tableName+"(){\n";
            content+="	}\n";
            content+="\n";
            //get set
            for (Centity centity : centities) {
            	content+="	public "+centity.getColumnType()+" "+centity.getColumnGetMetohdName()+"(){\n";
            	content+="		 return this."+centity.getColumnName()+";\n";
            	content+="	}\n\n";
            	content+="	public void "+centity.getColumnSetMetohdName()+"("+centity.getColumnType()+" "+centity.getColumnName()+"){\n";
            	content+="		 this."+centity.getColumnName()+" = "+centity.getColumnName()+";\n";
            	content+="	}\n\n";
			}
            content+="}";
            File f = new File(path + "/com/youi/entity/" + tableName + ".java");
            if (f.exists()) {
                System.out.println("文件存在");
            } else {
                System.out.println("文件不存在");
                f.createNewFile();// 不存在则创建
            }
            BufferedWriter output = new BufferedWriter(new FileWriter(f));
            output.write(content);
            output.close();
        } catch ( Exception e) {
            e.printStackTrace();
        }
	}
}

/**
 * 对象OR映射类
 * @author erdong.Chan
 *
 */
class Centity{
	
	private String columnName;//字段名
	private String columnType;//字段类型
	private String columnCommond;//字段注释
	
	private String columnGetMetohdName;//get
	private String columnSetMetohdName;//set
	
	public Centity(String columnName, String columnType, String columnCommond) {
		super();
		this.columnName = columnName;
		if (columnType!=null) {
			this.columnType =checkType(columnType);
		}
		this.columnCommond = columnCommond;
		if (columnName!=null) {
			this.columnGetMetohdName=checkGetName(columnName);
			this.columnSetMetohdName=checkSetName(columnName);
		}
	}

	public String getColumnName() {
		return columnName;
	}

	public void setColumnName(String columnName) {
		this.columnName = columnName;
	}

	public String getColumnType() {
		return columnType;
	}

	public void setColumnType(String columnType) {
		this.columnType = columnType;
	}

	public String getColumnCommond() {
		return columnCommond;
	}

	public void setColumnCommond(String columnCommond) {
		this.columnCommond = columnCommond;
	}
	
	public String getColumnGetMetohdName() {
		return columnGetMetohdName;
	}

	public void setColumnGetMetohdName(String columnGetMetohdName) {
		this.columnGetMetohdName = columnGetMetohdName;
	}

	public String getColumnSetMetohdName() {
		return columnSetMetohdName;
	}

	public void setColumnSetMetohdName(String columnSetMetohdName) {
		this.columnSetMetohdName = columnSetMetohdName;
	}

	/**
	 * 类型转换
	 * @param type
	 * @return
	 */
	private String checkType(String type) {
		if (type.equals("bigint")) {
			return "Long";
		}else if (type.equals("int")) {
			return "Integer";
		}else if (type.contains("varchar")||type.contains("text")) {
			return "String";
		}else if (type.contains("time")) {
			return "Date";
		}
		return null;
	}
	
	/**
	 * 获取get方法名
	 * @param columnName
	 * @return
	 */
	private String checkGetName(String columnName) {
		return "get"+columnName.substring(0, 1).toUpperCase()+columnName.substring(1,columnName.length());
	}
	
	/**
	 * 获取set方法名
	 * @param columnName
	 * @return
	 */
	private String checkSetName(String columnName) {
		return "set"+columnName.substring(0, 1).toUpperCase()+columnName.substring(1,columnName.length());
	}
	
}
